package leetcode.linkedList.p203;

/**
 * 
 * @Title: Solution203.java 
 * @Package leetcode 
 * @Description: 问题203：移除链表元素，不带头结点的链表方式删除，删除引用优化部分的代码
 * @author CandyWall   
 * @date 2021年1月4日 上午12:27:20 
 * @version V1.0
 */
/**
 * Definition for singly-linked list. public class ListNode { int val; ListNode
 * next; ListNode(int x) { val = x; } }
 */
public class Solution203_v2 {
	public ListNode removeElements(ListNode head, int val) {
		//头结点特殊处理
		//如果删除的元素都在头结点上
		while (head != null && head.val == val) {
			head = head.next;
		}
		
		//如果链表中的所有的元素都是要删除的节点，就直接返回空表头
		if(head == null) {
			return null;
		}
		
		ListNode prev = head;
		while(prev.next != null) {
			//如果当前节点后面的节点需要被删除
			if(prev.next.val == val) {
				prev.next = prev.next.next;
			} 
			//指针向后移
			else {
				prev = prev.next;
			}
		}
		return head;
	}
	
	public static void main(String[] args) {
		ListNode node = new ListNode(1);
		ListNode p = node;
		p.next = new ListNode(2);
		p = p.next;
		p.next = new ListNode(6);
		p = p.next;
		p.next = new ListNode(3);
		p = p.next;
		p.next = new ListNode(4);
		p = p.next;
		p.next = new ListNode(5);
		p = p.next;
		p.next = new ListNode(6);
		p = p.next;
		
		for(p = node; p != null; p = p.next) {
			System.out.print(p.val + "->");
		}
		System.out.println();
		node = new Solution203_v2().removeElements(node, 6);
		for(p = node; p != null; p = p.next) {
			System.out.print(p.val + "->");
		}
		/*ListNode p = node;
		for(p = node; p != null;p = p.next) {
			System.out.print(p.val + "->");
		}
		System.out.println();
		node = new Solution203_v1().removeElements(node, 1);
		for(p = node; p != null;p = p.next) {
			System.out.print(p.val + "->");
		}*/
	}
}


